package cn.lhl.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

/**
 * Created by datou on 2017/1/19.
 */
public class HibernateUtil  {
    private static Configuration configuration;
    private  static SessionFactory sessionFactory;
    private  static  ThreadLocal threadLocal;
    private  static Transaction ts;
    static {
        configuration= new Configuration();
        sessionFactory=configuration.configure().buildSessionFactory();
        threadLocal=new ThreadLocal();

    }
    public static Session getSession(){
        Session session=(Session) threadLocal.get();
        if(session==null){
            session=sessionFactory.openSession();
            threadLocal.set(session);
        }
        ts=session.beginTransaction();

        return  session;
    }
    public static void close(){
        Session session=(Session) threadLocal.get();
        ts.commit();
        session.close();
        threadLocal.set(null);
    }

}
